<template>
  <div
    class="dialog animated"
    :class="open ? 'fadeIn' : 'fadeOut'"
    v-show="show"
    :style="{ visibility: visible ? 'visible' : 'hidden' }"
  >
    <div class="panel animated" :class="open ? 'zoomIn' : ''">
      <div class="title">
        {{ title }}
        <div class="close" @click="cancel()"></div>
      </div>
      <div>
        <el-form :model="campusData" ref="campusData" label-width="240px">
          <el-form-item label="机构名称" :rules="[{ required: true, message: '' }]">
            <el-input
              clearable
              style="width:50%"
              v-model="campusData.orgName"
              placeholder="请输入机构名称"
              :disabled="isEnable"
            ></el-input>
          </el-form-item>
          <el-form-item label="机构类型" :rules="[{ required: true, message: '' }]">
            <el-select
              style="width:50%"
              v-model="campusData.orgMode"
              :disabled="isShow || isOrg"
              clearable
              placeholder="请选择机构类型"
            >
              <el-option
                v-for="item in orgModeList"
                :key="item.name"
                :label="item.name"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="机构电话">
            <el-input
              clearable
              style="width:50%"
              maxlength="12"
              :disabled="isShow"
              v-model="campusData.phone"
              placeholder="请输入机构电话，如：020-12345678"
            ></el-input>
          </el-form-item>
          <el-form-item label="机构logo">
            <el-upload
              class="avatar-uploader"
			  style="margin-top:0.36rem;"
              :action="uploadUrl"
              :show-file-list="false"
              :disabled="isShow"
              :data="uploadData"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :headers="headers"
              :on-error="uploadError"
              accept=".jpg, .png"
            >
              <img @click="clickPic(false)" v-if="imgUrl_44" :src="imgUrl_44" class="avatar" />
              <img
                @click="clickPic(false)"
                :disabled="isShow"
                src="../../../assets/img/system_set/def_logo1.jpg"
                v-else
              />
              <div
                slot="tip"
                class="el-upload__tip"
                style="line-height: 0.3rem;margin-top:-0.1rem;font-size:0.14rem;"
              >44x44</div>
            </el-upload>
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :disabled="isShow"
              :data="uploadData"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :headers="headers"
              :on-error="uploadError"
              accept=".jpg, .png"
            >
              <img @click="clickPic(true)" v-if="imgUrl_202" :src="imgUrl_202" class="avatar" />
              <img
                @click="clickPic(true)"
                :disabled="isShow"
                src="../../../assets/img/system_set/def_logo2.jpg"
                v-else
              />
              <div
                slot="tip"
                class="el-upload__tip"
                style="line-height: 0.3rem;margin-top:-0.1rem;font-size:0.14rem;padding-left:0.7rem"
              >210x82</div>
            </el-upload>
          </el-form-item>
          <el-form-item label="所属公司">
            <el-input
              clearable
              :disabled="isShow"
              style="width:50%"
              v-model="campusData.belongCompany"
              placeholder="请输入所属公司"
            ></el-input>
          </el-form-item>
          <el-form-item label="机构所在地区">
            <el-cascader
              clearable
              :disabled="isShow"
              :props="defaultProps"
              style="width:50%"
              :options="citys"
              v-model="campusData.regionAddress"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="机构详细地址">
            <el-input
              clearable
              :disabled="isShow"
              style="width:50%"
              maxlength="50"
              v-model="campusData.detailedAddress"
              placeholder="请输入机构详细地址"
            ></el-input>
          </el-form-item>
          <el-form-item label="负责人" :rules="[{ required: true, message: '' }]">
            <el-input
              clearable
              :disabled="isShow || isOrg"
              style="width:50%"
              v-model="campusData.adminUserName"
              placeholder="请输入负责人姓名"
            ></el-input>
          </el-form-item>
          <el-form-item label="手机号" :rules="[{ required: true, message: '' }]">
            <el-input
              clearable
              :disabled="isShow || isOrg"
              style="width:50%"
              type="text"
              maxlength="11"
              oninput="value=value.replace(/[^\d]/g,'')"
              onpaste="return false;"
              v-model="campusData.adminPhone"
              placeholder="请输入负责人手机号，并为该机构管理员账号"
            ></el-input>
          </el-form-item>
          <el-form-item label="合作类型" :rules="[{ required: true, message: '' }]">
            <el-select
              style="width:50%"
              :disabled="isShow || isOrg"
              v-model="campusData.cooperateOrgMode"
              @change="orgModeChange"
              clearable
              placeholder="请选择合作类型"
            >
              <el-option
                v-for="item in cooperationModeList"
                :key="item.name"
                :label="item.name"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="服务期限"
            v-if="campusData.cooperateOrgMode != 1"
            :rules="[{ required: true, message: '' }]"
          >
            <el-row style="width:50%">
              <el-col :span="10">
                <el-date-picker
                  type="date"
                  :disabled="isShow || isOrg"
                  placeholder="开始日期"
                  v-model="campusData.serveStartTime"
                  style="width: 100%;"
                ></el-date-picker>
              </el-col>
              <el-col style="text-align: center;" :span="3">-</el-col>
              <el-col :span="11">
                <el-date-picker
                  type="date"
                  :disabled="isShow || isOrg"
                  placeholder="结束日期"
                  v-model="campusData.serveEndTime"
                  style="width: 100%;"
                ></el-date-picker>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              clearable
              style="width:50%"
              :disabled="isShow"
              maxlength="50"
              v-model="campusData.remark"
              placeholder="请输入补充说明信息"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="btn_div" v-if="!isShow">
        <div class="btn_sure" @click="sure()">确 认</div>
        <div class="btn_cancel" @click="cancel()">取 消</div>
      </div>
    </div>
  </div>
</template>

<script>
import citys from "@/../static/citys.json";
var vm;
export default {
  data: function() {
    return {
      show: false,
      open: false,
      visible: false,
      isAdd: true, //是否为新增
      isShow: false, //是否为查看
      isEnable: false, //是否可编辑名称
      isOrg: false, //是否为机构管理员
      title: "",
      citys: [],
      isTwo: false,
      imgUrl_44: "",
      imgUrl_202: "",
      campusData: {},
      uploadData: {
        content: "orglogo"
      },
      cooperationModeList: [],
      uploadUrl: window.config.baseUrl + "/file/upload",
      orgModeList: [],
      defaultProps: {
        label: "label",
        value: "label",
        children: "children"
      },
      headers: {
        // 'Content-Type': 'multipart/form-data',
        token: tool.getItem(lsKey.token)
      }
    };
  },
  methods: {
    clickPic(isTwo) {
      vm.isTwo = isTwo;
    },
    orgModeChange: function(val) {
      if (val == 1) {
        vm.campusData.serveStartTime = "1946-02-14";
        vm.campusData.serveEndTime = "2999-12-30";
      } else {
        vm.campusData.serveStartTime = "";
        vm.campusData.serveEndTime = "";
      }
    },
    uploadError: function(response, file) {
      console.log("上传文件失败response" + response);
    },
    handleAvatarSuccess(res, file) {
      if (res.status != "success") {
        this.$message.error("上传文件失败，" + res.data.result);
      } else {
        if (!vm.isTwo) {
          this.imgUrl_44 = res.data.url;
        } else {
          this.imgUrl_202 = res.data.url;
        }
      }
    },
    beforeAvatarUpload(file) {
		console.log(file);
      const isJPG = file.type === "image/jpeg" || "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传logo图片只能是 JPG/PNG 格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传logo图片大小不能超过 2MB!");
        return false;
      }
      let fontSize;
      if (!vm.isTwo) {
        fontSize = "44x44";
      } else {
        fontSize = "210x82";
      }
      
      const isSize = new Promise(function(resolve, reject) {
        let width = fontSize.split("x")[0];
        let height = fontSize.split("x")[1];
        let _URL = window.URL || window.webkitURL;
        let image = new Image();
        image.onload = function() {
          let value = image.width == width && image.height == height;
          value ? resolve() : reject();
        };
        image.src = _URL.createObjectURL(file);
      }).then(
        () => {
		  return file;
        },
        () => {
          tool.message({
            showClose: true,
            message: "上传logo图片尺寸不符合，应为" + fontSize,
            type: "warning"
		  });
		  return Promise.reject();
        }
	  );
	  return isSize;
    },
    init: function(data) {
      vm.show = true;
      setTimeout(function() {
        vm.open = true;
        vm.visible = true;
      }, 11);
      let user = tool.getItem(lsKey.user, true); //得到当前用户信息
      //获取数据字典
      let dicdata = tool.getItem(lsKey.dict, true);
      vm.cooperationModeList = dicdata["cooperate_org_mode"];
      vm.orgModeList = dicdata["organization_type"];
      vm.citys = citys;
      // console.log(citys);
      if (data.orgId != null) {
        vm.isAdd = false;
        vm.title = "编辑机构";
        vm.isEnable = true;
        if (data.isShow) {
          vm.isShow = true;
          vm.title = "查看机构";
        }
        let campusData = data;
        campusData.regionAddress = [];
        campusData.detailedAddress = "";
        let str = campusData.orgAddr.split("/");
        if (str.length > 1) {
          campusData.regionAddress.push(str[0], str[1], str[2]);
          campusData.detailedAddress = str[3];
        } else {
          campusData.detailedAddress = campusData.orgAddr;
        }
        if (campusData.logoLinker != "") {
          vm.imgUrl_44 = campusData.logoLinker.split(",")[0];
          vm.imgUrl_202 = campusData.logoLinker.split(",")[1];
        } else {
          vm.imgUrl_44 = "";
          vm.imgUrl_202 = "";
        }

        if (user.roleMode > 1) {
          this.$message.error("该账号无权限修改校区");
          cancel();
        }
        vm.isOrg = user.roleMode == 1;
        vm.campusData = campusData;
        console.log(vm.campusData);
      } else {
        vm.isEnable = false; //是否可编辑名称
        vm.isOrg = false; //是否为机构管理员
        vm.isAdd = true;
        vm.title = "新增机构";
        vm.campusData = {
          orgName: "",
          phone: "",
          logoLinker: "",
          orgMode: "",
          regionAddress: [],
          detailedAddress: "",
          belongCompany: "",
          adminUserName: "",
          adminPhone: "",
          cooperateOrgMode: "",
          serveStartTime: "",
          serveEndTime: "",
          remark: ""
        };
        if (user.roleMode > 0) {
          this.$message.error("该账号无权限新增机构");
          vm.cancel();
        }
      }
    },
    cancel: function() {
      //隐藏弹窗
      vm.open = false;
      setTimeout(function() {
        vm.show = false;
        vm.visible = false;
        vm.isAdd = true;
        vm.isShow = false;
        vm.isEnable = false;
        vm.isTwo = false;
        vm.imgUrl_44 = "";
          vm.imgUrl_202 = "";
      }, 11);
    },
    sure: function() {
      console.log(vm.campusData);
      if (vm.campusData.orgName == "") {
        this.$message.warning("机构名称不能为空");
        return;
      }
      if (!tool.judge("classname", vm.campusData.orgName)) {
        this.$message.warning("请输入有效的机构名称");
        return;
      }
      if (vm.campusData.orgMode == "") {
        this.$message.warning("机构类型不能为空");
        return;
      }
      if (
        (vm.imgUrl_44 == "" && vm.imgUrl_202 != "") ||
        (vm.imgUrl_44 != "" && vm.imgUrl_202 == "")
      ) {
        this.$message.warning("如需上传机构logo，则必须上传两种分辨率的logo");
        return;
      }
      if (vm.campusData.adminUserName == "") {
        this.$message.warning("机构负责人不能为空");
        return;
      }
      if (!tool.judge("name", vm.campusData.adminUserName)) {
        this.$message.warning("请输入有效的机构负责人");
        return;
      }
      if (vm.campusData.adminPhone == "") {
        this.$message.warning("机构负责人手机不能为空");
        return;
      }
      if (!tool.judge("phone", vm.campusData.adminPhone)) {
        this.$message.warning("手机号不匹配!");
        return;
      }
      if (vm.campusData.cooperateOrgMode == "") {
        this.$message.warning("合作模式不能为空");
        return;
      }
      if (vm.campusData.serveStartTime == "") {
        this.$message.warning("服务开始时间不能为空");
        return;
      }
      if (vm.campusData.serveEndTime == "") {
        this.$message.warning("服务结束时间不能为空");
        return;
      }
      if (vm.campusData.regionAddress.length > 0) {
        vm.campusData.orgAddr =
          vm.campusData.regionAddress[0] +
          "/" +
          vm.campusData.regionAddress[1] +
          "/" +
          vm.campusData.regionAddress[2] +
          "/" +
          vm.campusData.detailedAddress;
      } else {
        vm.campusData.orgAddr = vm.campusData.detailedAddress;
      }
      if (vm.campusData.serveStartTime instanceof Date) {
        vm.campusData.serveStartTime = tool.DateToString(
          vm.campusData.serveStartTime,
          "yyyy-MM-dd"
        );
      }
      if (vm.campusData.serveEndTime instanceof Date) {
        vm.campusData.serveEndTime = tool.DateToString(
          vm.campusData.serveEndTime,
          "yyyy-MM-dd"
        );
      }
      if (vm.imgUrl_44 != "") {
        vm.campusData.logoLinker = vm.imgUrl_44 + "," + vm.imgUrl_202;
      }
      // vm.campusData.serveEndTime = tool.DateToString(vm.campusData.serveEndTime,"yyyy-MM-dd HH:mm:ss");
      vm.campusData._wait = "";
      if (vm.isAdd) {
        api.orgAdd(vm.campusData).then(function(data) {
          console.log(data);
          if (data.resultCode == 2000) {
            vm.$message({
              message: "添加成功",
              type: "success"
            });
            vm.$emit("callback", "添加成功");
            vm.cancel();
          } else {
            vm.$message.error(data.message);
          }
        });
      } else {
        // paras.userId = vm.accountData.userId;
        api.orgUpdate(vm.campusData).then(function(data) {
          console.log(data);
          if (data.resultCode == 2000) {
            vm.$message({
              message: "修改成功",
              type: "success"
            });
            vm.$emit("callback", "修改成功");
            vm.cancel();
          } else {
            vm.$message.error(data.message);
          }
        });
      }
    }
  },
  created: function() {
    vm = this;
  }
};
</script>
<style scoped src="@/style/module/dialog.css"></style>
<style scoped>
.btn_div {
  padding: 0 0 0.3rem 0;
}
.panel {
  width: 10rem;
  padding-bottom: 0.2rem;
}
.ruleForm {
  padding-left: 0.5rem;
}
.el-radio-group {
  line-height: inherit;
}
.tree {
  padding: 0.1rem 0.5rem;
  /* max-height: 5.4rem; */
}
.el-col {
  border-radius: 4px;
}
.bg-purple {
  background: #d3dce6;
}
.grid-content {
  line-height: 0.5rem;
  text-align: center;
}
.avatar-uploader {
  float: left;
  margin-left: 0.2rem;
}
.avatar-uploader .el-upload {
  border: 1px dashed #453374;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 78px;
  line-height: 78px;
  text-align: center;
}
.avatar {
  display: block;
  object-fit: cover;
}
</style>
